package com.yanqu.road.server.gameplayer.module.activity.memorypieces;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.ActivityRewardResult;
import com.yanqu.road.entity.activity.args.MemoryPiecesProgressArgs;
import com.yanqu.road.entity.activity.memorypieces.MemoryPiecesProgress;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogMemoryPiecesLightUp;
import com.yanqu.road.logic.bussiness.activity.MemoryPiecesBusiness;
import com.yanqu.road.pb.activity.MemoryPiecesProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.memorypieces.MemoryPiecesMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class MemoryPiecesModule extends GeneralModule {

    /**
     * 用户数据
     */
    private MemoryPiecesProgress userData;

    public MemoryPiecesModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.MemoryPieces.getValue())) {
            ActivityInfo activityInfo = MemoryPiecesMgr.getActivityInfo();
            if (ActivityMgr.activityInShowTime(activityInfo)) {
                userData = MemoryPiecesBusiness.getMemoryPiecesProgressMap(activityInfo.getActivityId(), player.getUserId());
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                MemoryPiecesBusiness.addMemoryPiecesProgress(userData);
            } else if (userData.isUpdateOption()) {
                MemoryPiecesBusiness.updateMemoryPiecesProgress(userData);
            }

        }
        return true;
    }

    @Override
    public void afterLogin() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.MemoryPieces.getValue())) {
            initUserData();
            syncData();
        }
    }

    public void initSystem() {
        ActivityInfo activityInfo = MemoryPiecesMgr.getActivityInfo();
        if (activityInfo == null) {
            return;
        }
        if (SystemOpenMgr.systemOpen(player, eSystemId.MemoryPieces.getValue())) {
            initUserData();
            syncData();
        }
    }

    public synchronized void initUserData() {
        ActivityInfo activityInfo = MemoryPiecesMgr.getActivityInfo();
        if (activityInfo == null) {
            return;
        }
        if (userData != null && userData.getActivityId() == activityInfo.getActivityId()) {
            // 检测是否开启新的进度
            if (userData.getLightPieces().size() == MemoryPiecesMgr.puzzleItemCostList.get(userData.getPiecesId() - 1).size()
                    && userData.getPiecesId() < MemoryPiecesMgr.puzzleItemCostList.size()) {
                // 开启下一个拼图
                userData.setPiecesId(userData.getPiecesId() + 1);
                userData.setLightPieces(new ArrayList<>());
            }
            return;
        }

        MemoryPiecesProgress progress = new MemoryPiecesProgress();
        progress.setActivityId(activityInfo.getActivityId());
        progress.setUserId(getUserId());
        progress.setPiecesId(1);
        progress.setLightPieces(new ArrayList<>());
        progress.setInsertOption();
        userData = progress;
    }

    public void syncData() {
        if (userData == null) {
            return;
        }
        // 同步数据
        player.sendPacket(ClientProtocol.U_MEMORY_PIECES_DATA, getPiecesInfo());
    }

    /**
     * 获取拼图信息
     */
    public MemoryPiecesProto.MemoryPiecesRespMsg.Builder getPiecesInfo() {
        MemoryPiecesProto.MemoryPiecesRespMsg.Builder respMsg = MemoryPiecesProto.MemoryPiecesRespMsg.newBuilder();
        ActivityInfo activityInfo = MemoryPiecesMgr.getActivityInfo();
        if (activityInfo == null) {
            return respMsg;
        }
        // 获取当前用户点亮的信息
        if (userData == null) {
            return respMsg;
        }
        respMsg.setUserData(createDataMsgBuilder(userData));
        return respMsg;
    }


    /**
     * 点亮拼图
     */
    public int piecesLightUp(int index) {
        ActivityInfo activityInfo = MemoryPiecesMgr.getInTimeActivityInfo();
        if (activityInfo == null) {
            return GameErrorCode.E_MEMORY_PIECES_NO_OPEN;
        }
        // 获取当前用户点亮的信息
        if (userData == null) {
            return GameErrorCode.E_MEMORY_PIECES_NO_UNLOCK;
        }
        // 获取当前拼图id
        int piecesId = userData.getPiecesId();
        List<Integer> lightPieces = userData.getLightPieces();
        // 检查索引是否有效
        if (index < 0 || index >= MemoryPiecesMgr.puzzleItemCostList.get(piecesId - 1).size()) {
            return GameErrorCode.E_MEMORY_PIECES_INDEX_INVALID;
        }
        if (lightPieces.contains(index)) {
            return GameErrorCode.E_MEMORY_PIECES_ALREADY_LIGHT;
        }
        // 消耗碎片
        long cost = MemoryPiecesMgr.puzzleItemCostList.get(piecesId - 1).get(index);
        //消耗解锁材料
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(MemoryPiecesMgr.ZHOUNIAN_PUZZLE_ITEM_ID, cost), eLogMoneyType.MemoryPieces, eLogMoneyType.MemoryPiecesLightCost)) {
            return GameErrorCode.E_MEMORY_PIECES_NO_ENOUGH;
        }
        // 点亮碎片
        lightPieces.add(index);
        userData.setLightPieces(lightPieces);
        // 更新任务进度
        player.notifyListener(eGamePlayerEventType.MemoryPiecesProgress.getValue(), new MemoryPiecesProgressArgs(piecesId, lightPieces.size()));

        // 点亮日志
        LogMgr.addLogMemoryPiecesLightUp(new LogMemoryPiecesLightUp(
                player.getUserId(),
                activityInfo.getActivityId(),
                piecesId,
                index,
                lightPieces.size(),
                System.currentTimeMillis()
        ));

        MemoryPiecesProto.MemoryPiecesLightUpRespMsg.Builder respMsg = MemoryPiecesProto.MemoryPiecesLightUpRespMsg.newBuilder();
        // 检查是否完成
        if (lightPieces.size() == MemoryPiecesMgr.puzzleItemCostList.get(piecesId - 1).size()) {
            // 当前拼图完成,获取奖励,开启下一个拼图
            // 获取剩余的未领奖的奖励
            ActivityRewardResult rewardResult = oneKeyGetPiecesTaskReward(activityInfo.getActivityId(), userData);
            respMsg.setReward(rewardResult.getReward());
            // 判断是否有下一个拼图
            if (piecesId < MemoryPiecesMgr.puzzleItemCostList.size()) {
                // 开启下一个拼图
                userData.setPiecesId(piecesId + 1);
                userData.setLightPieces(new ArrayList<>());
            }
        }
        respMsg.setRet(0);
        respMsg.setUserData(createDataMsgBuilder(userData));
        player.sendPacket(ClientProtocol.U_MEMORY_PIECES_LIGHT, respMsg);
        return 0;
    }

    /**
     * 一键领取拼图任务进度奖励
     */
    public ActivityRewardResult oneKeyGetPiecesTaskReward(int activityId, MemoryPiecesProgress userData) {
        List<Integer> conditionIdList = new ArrayList<>();
        MemoryPiecesMgr.memoryPiecesConditionInfoList.forEach(info -> {
            List<BigInteger> paramList = info.getParamList();
            if (info.getType() == eGamePlayerEventType.MemoryPiecesProgress.getValue()
                    && userData.getPiecesId() == paramList.get(0).intValue() && userData.getLightPieces().size() >= paramList.get(1).intValue()) {
                conditionIdList.add(info.getConditionId());
            }
        });
        // 一键领取
        return player.getModule(ActivityModule.class).getActivityRewardOneKey(activityId, conditionIdList);
    }

    /**
     * 构造返回数据
     */
    public static MemoryPiecesProto.MemoryPiecesDetailTemp.Builder createDataMsgBuilder(MemoryPiecesProgress userData) {
        MemoryPiecesProto.MemoryPiecesDetailTemp.Builder builder = MemoryPiecesProto.MemoryPiecesDetailTemp.newBuilder();
        builder.setPiecesId(userData.getPiecesId());
        builder.setLightPieces(StringUtils.listToString(userData.getLightPieces(), ","));
        return builder;
    }


}
